<template>
  <div class="page business-analysis">
    <DateChoice ref="DateChoice" v-on:listenToDateChoice="getSelectDateValue" />
    <StoreChoice
      ref="StoreChoice"
      :current="[]"
      v-if="role"
      :multipleChoice="false"
      v-on:listenToStoreSelect="getSelectStoreValue"
      :hasTotal="true"
    />
    <storeCompare ref="storeCompare" :filterData="filterData"></storeCompare>
    <orderSource ref="orderSource" :orderSourceParam="filterData" :orderSourceTab="orderSourceTab"></orderSource>
    <menuList ref="menuList" :list="menuList" @itemClick="handleMenu"></menuList>
    <calendarDay ref="calendarDay" @reportSelect="reportSelect" @rangeMin="handleRangeMin"></calendarDay>
    <calendarWeek ref="calendarWeek" @reportSelect="reportSelect" @rangeMin="handleRangeMin"></calendarWeek>
    <calendarMonth ref="calendarMonth" @reportSelect="reportSelect" @rangeMin="handleRangeMin"></calendarMonth>
    <div class="scroll-view">
      <customHeader
        @middleCallBack="handleClickSelectStore"
        @rightCallBack="toggleMenu"
        :noLeft="true"
        v-if="role"
      >
        <i ref="menuBtn" class="zhk-gd"></i>
        <div slot="slotMiddle">
          {{storeNameFormate()}}
          <i class="zhk-list_rarrow arrow-down"></i>
        </div>
      </customHeader>
      <customHeader @rightCallBack="toggleMenu" :noLeft="true" v-else>
        <i ref="menuBtn" class="zhk-gd"></i>
        <div slot="slotMiddle">{{shopName}}</div>
      </customHeader>
      <div class="page-body">
        <v-loadmore
          :top-method="loadTop"
          :topDistance="50"
          :auto-fill="false"
          ref="loadmore"
          @top-status-change="handleTopChange"
          style="height:100%"
        >
          <ul class="filter" v-show="reportFilter.reportType=='day'" >
            <li class="ope" :class="{disabled:dayPreDisabled}" @click='handleDateChange("day","pre")'>前一天</li>
            <li class="date" @click="handleMenu('day')">
              <div>{{reportFilter.dateLabel}}</div>
            </li>
            <li class="ope" :class="{disabled:dayNextDisabled}" @click='handleDateChange("day","next")'>后一天</li>
          </ul>
          <ul class="filter" v-show="reportFilter.reportType=='week'">
            <li class="ope" :class="{disabled:weekPreDisabled}" @click='handleDateChange("week","pre")'>前一周</li>
            <li class="date" @click="handleMenu('week')">
              <div>{{reportFilter.dateLabel}}</div>
            </li>
            <li class="ope" :class="{disabled:weekNextDisabled}" @click='handleDateChange("week","next")'>后一周</li>
          </ul>
          <ul class="filter" v-show="reportFilter.reportType=='month'">
            <li class="ope"  :class="{disabled:monthPreDisabled}" @click='handleDateChange("month","pre")'>前一月</li>
            <li class="date" @click="handleMenu('month')">
              <div>{{reportFilter.dateLabel}}</div>
            </li>
            <li class="ope" :class="{disabled:monthNextDisabled}" @click='handleDateChange("month","next")'>后一月</li>
          </ul>
          <ul
            class="filter"
            v-show="reportFilter.reportType=='custom'"
            @click="handleMenu('custom')"
          >
            <li class="date custom">
              <div>{{reportFilter.dateLabel}}</div>
            </li>
          </ul>
          <div class="trade-summary">
            <div class="section-title">交易汇总</div>
            <div class="ts-content">
              <div class="top">
                <div class="total-get">
                  <span>实收金额(元)</span>
                  <div>{{CommonUtil.moneyFormate(tradeSum.todayAmt)}}</div>
                </div>
                <div
                  class="discount"
                >优惠金额(元)：{{CommonUtil.moneyFormate(tradeSum.todaySupplierDiscount)}}</div>
              </div>
              <ul class="bottom">
                <li>
                  <div class="money">
                    <span>订单金额(元)</span>
                    <div>{{CommonUtil.moneyFormate(tradeSum.todayOrderAmt)}}</div>
                  </div>
                  <div class="amount">订单笔数(笔)：{{tradeSum.todayOrderCnt}}</div>
                </li>
                <li>
                  <div class="money">
                    <span>退款金额(元)</span>
                    <div>{{CommonUtil.moneyFormate(tradeSum.todayRefundAmt)}}</div>
                  </div>
                  <div class="amount">退款笔数(笔)：{{tradeSum.todayRefundCnt}}</div>
                </li>
              </ul>
            </div>
          </div>
          <div class="get-way">
            <ul class="tab-bar" style="margin:0;">
              <li
                class="checked"
                :key="index"
                v-for="(item,index) in tabCompent.tabList"
                @click="toggleTab(tabCompent,index)"
                :class="{selected:index == tabCompent.tabIndex}"
              >{{item}}</li>
            </ul>
            <div class="section chart-wrap" v-if="0 == tabCompent.tabIndex">
              <ve-pie :data="chartData1" :settings="chartSettings" :colors="pieColors"></ve-pie>
              <p class="chart-remark">
                备注：
                <br />上述数据为顾客在店铺消费的付款方式，不包含充值会员储值卡的数据。
                <br />
              </p>
            </div>
            <div class="section chart-wrap" v-if="1 == tabCompent.tabIndex">
              <ve-ring :data="chartData" :settings="chartSettings"></ve-ring>
              <p class="chart-remark">
                备注：
                <br />对比实际收入来源情况。
                <br />收银：顾客在店铺消费所产生的实际收入金额（不包括使用会员储值卡支付的消费）。
                <br />储值：顾客在店铺充值会员储值卡所产生的实际收入金额。
                <br />
              </p>
            </div>
          </div>
          <div class="get-way chart-width">
            <ul class="tab-bar" style="margin:0;">
              <li
                class="checked"
                :key="index"
                v-for="(item,index) in tabCompent4.tabList"
                @click="toggleTab(tabCompent4,index)"
                :class="{selected:index == tabCompent4.tabIndex}"
              >{{item}}</li>
            </ul>
            <div class="section chart-wrap" v-show="0 == tabCompent4.tabIndex">
              <ul class="table">
                <li>
                  <div>收银员</div>
                  <div>实收金额(元)</div>
                  <div>笔数</div>
                </li>
              </ul>
              <div class="scroll-wrap">
                <ul class="table">
                  <li :key="index" v-for="(item,index) in orderSource">
                    <div v-html="item.staticsName"></div>
                    <div>{{ item.totalPayAmt }}</div>
                    <div>{{ item.totalOrderCnt }}</div>
                  </li>
                </ul>
              </div>
            </div>
            <div class="section chart-wrap" v-if="1 == tabCompent4.tabIndex">
              <ul class="table">
                <li>
                  <div>收款码</div>
                  <div>实收金额(元)</div>
                  <div>笔数</div>
                </li>
              </ul>
              <div class="scroll-wrap">
                <ul class="table">
                  <li :key="index" v-for="(item,index) in orderSource">
                   <div v-html="item.staticsName"></div>
                    <div>{{ item.totalPayAmt }}</div>
                    <div>{{ item.totalOrderCnt }}</div>
                  </li>
                </ul>
              </div>
            </div>
            <div class="section chart-wrap" v-if="2 == tabCompent4.tabIndex">
              <ul class="table">
                <li>
                  <div>设备</div>
                  <div>实收金额(元)</div>
                  <div>笔数</div>
                </li>
              </ul>
              <div class="scroll-wrap">
                <ul class="table">
                  <li :key="index" v-for="(item,index) in orderSource">
                    <div v-html="item.staticsName"></div>
                    <div>{{ item.totalPayAmt }}</div>
                    <div>{{ item.totalOrderCnt }}</div>
                  </li>
                </ul>
              </div>
            </div>
            <div v-show="!orderSource.length" class="no-more">
                <span>暂无数据</span>
            </div>
            <a class="all-source" @click="handleOrderSourceAll" v-show="orderSourceTotalCount>5">
              <span>查看全部</span>
              <i class="zhk-list_rarrow"></i>
            </a>
          </div>
          <div class="zhk-statistics">
            <div class="section-title">同福业务统计</div>
            <div class="swipe-wrap">
              <swiper :options="swiperOption" ref="mySwiper">
                <swiper-slide>
                  <div class="swipe-item">
                    <div class="type">收银</div>
                    <div class="ts-content">
                      <div class="top">
                        <div class="total-get">
                          <span>实收金额(元)</span>
                          <div>{{trafficStatistics[0].todayReceiveAmt}}</div>
                        </div>
                        <div class="discount">优惠金额：{{trafficStatistics[0].todayReceiveDiscountAmt}}</div>
                      </div>
                      <ul class="bottom">
                        <li>
                          <div class="money">
                            <span>订单金额(元)</span>
                            <div>{{trafficStatistics[0].todayReceiveOrderAmt}}</div>
                          </div>
                          <div class="amount">订单笔数(笔)：{{trafficStatistics[0].todayReceiveOrderCnt}}</div>
                        </li>
                        <li>
                          <div class="money">
                            <span>退款金额(元)</span>
                            <div>{{trafficStatistics[0].todayReceiveRefAmt}}</div>
                          </div>
                          <div class="amount">退款笔数(笔)：{{trafficStatistics[0].todayReceiveRefCnt}}</div>
                        </li>
                      </ul>
                    </div>
                  </div>
                </swiper-slide>
                <swiper-slide v-if="isKb">
                  <div class="swipe-item">
                    <div class="type">在线商品</div>
                    <div class="ts-content">
                      <div class="top">
                        <div class="total-get">
                          <span>实收金额</span>
                          <div>{{trafficStatistics[1].todayOnlineGoodsUseAmt}}</div>
                        </div>
                        <div class="discount"></div>
                      </div>
                      <ul class="bottom">
                        <li>
                          <div class="money">
                            <span>售出商品</span>
                            <div>{{trafficStatistics[1].onlineGoodsTakenCnt}}</div>
                          </div>
                        </li>
                        <li>
                          <div class="money">
                            <span>已核销</span>
                            <div>{{trafficStatistics[1].onlineGoodsUseCnt}}</div>
                          </div>
                        </li>
                      </ul>
                      <!-- <p class="tip">
											数据来自第三方平台会有偏差，仅供参考
                      </p>-->
                    </div>
                  </div>
                </swiper-slide>
                <swiper-slide v-if="isKb">
                  <div class="swipe-item">
                    <div class="type">会员卡储值</div>
                    <div class="ts-content">
                      <div class="top">
                        <div class="total-get">
                          <span>实收金额(元)</span>
                          <div>{{trafficStatistics[2].todayCardRechargeAmt}}</div>
                        </div>
                        <div class="discount">优惠金额：{{trafficStatistics[2].todayCardRecDisAmt}}</div>
                      </div>
                      <ul class="bottom">
                        <li>
                          <div class="money">
                            <span>储值金额(元)</span>
                            <div>{{trafficStatistics[2].todayCardRecOrderAmt}}</div>
                          </div>
                        </li>
                        <li>
                          <div class="money">
                            <span>充值笔数(笔)</span>
                            <div>{{trafficStatistics[2].todayCardRecCnt}}</div>
                          </div>
                        </li>
                        <!-- <li>
												<div class="money">
													<span>退款金额(元)</span>
													<div>{{trafficStatistics[2].todayReceiveAmt}}</div>
												</div>
												<div class="amount">
													退款笔数(笔)：{{trafficStatistics[2].todayReceiveAmt}}
												</div>
                        </li>-->
                      </ul>
                    </div>
                  </div>
                </swiper-slide>

                <swiper-slide v-if="isKb">
                  <div class="swipe-item">
                    <div class="type">会员卡消费</div>
                    <div class="ts-content">
                      <div class="top">
                        <div class="total-get">
                          <span>消费实扣</span>
                          <div>{{trafficStatistics[3].todayCardConsAmt}}</div>
                        </div>
                        <div class="discount">优惠金额：{{trafficStatistics[3].todayCardConsDisAmt}}</div>
                      </div>
                      <ul class="bottom">
                        <li>
                          <div class="money">
                            <span>订单金额(元)</span>
                            <div>{{trafficStatistics[3].todayCardConsOrderAmt}}</div>
                          </div>
                          <div class="amount">订单笔数(笔)：{{trafficStatistics[3].todayCardConsOrderCnt}}</div>
                        </li>
                        <li>
                          <div class="money">
                            <span>退款金额(元)</span>
                            <div>{{trafficStatistics[3].todayCardConsRefAmt}}</div>
                          </div>
                          <div class="amount">退款笔数(笔)：{{trafficStatistics[3].todayCardConsRefCnt}}</div>
                        </li>
                      </ul>
                    </div>
                  </div>
                </swiper-slide>

                <swiper-slide v-if="isKb">
                  <div class="swipe-item">
                    <div class="type">扫码点餐</div>
                    <div class="ts-content">
                      <div class="top">
                        <div class="total-get">
                          <span>实收金额(元)</span>
                          <div>{{trafficStatistics[4].todayScanAmt}}</div>
                        </div>
                        <div class="discount">优惠金额：{{trafficStatistics[4].todayScanDiscountAmt}}</div>
                      </div>
                      <ul class="bottom">
                        <li>
                          <div class="money">
                            <span>订单金额(元)</span>
                            <div>{{trafficStatistics[4].todayScanOrderAmt}}</div>
                          </div>
                          <div class="amount">订单笔数(笔)：{{trafficStatistics[4].todayScanOrderCnt}}</div>
                        </li>
                        <li>
                          <div class="money">
                            <span>退款金额(元)</span>
                            <div>{{trafficStatistics[4].todayScanRefAmt}}</div>
                          </div>
                          <div class="amount">退款笔数(笔)：{{trafficStatistics[4].todayScanRefCnt}}</div>
                        </li>
                      </ul>
                    </div>
                  </div>
                </swiper-slide>

                <swiper-slide v-if="isKb">
                  <div class="swipe-item">
                    <div class="type">口碑点餐</div>
                    <div class="ts-content">
                      <div class="top">
                        <div class="total-get">
                          <span>实收金额(元)</span>
                          <div>{{trafficStatistics[5].todayAppointAmt}}</div>
                        </div>
                        <div class="discount">优惠金额：{{trafficStatistics[5].todayAppointDiscountAmt}}</div>
                      </div>
                      <ul class="bottom">
                        <li>
                          <div class="money">
                            <span>订单金额(元)</span>
                            <div>{{trafficStatistics[5].todayAppointOrderAmt}}</div>
                          </div>
                          <div class="amount">订单笔数(笔)：{{trafficStatistics[5].todayAppointOrderCnt}}</div>
                        </li>
                        <li>
                          <div class="money">
                            <span>退款金额(元)</span>
                            <div>{{trafficStatistics[5].todayAppointRefAmt}}</div>
                          </div>
                          <div class="amount">退款笔数(笔)：{{trafficStatistics[5].todayAppointRefundCnt}}</div>
                        </li>
                      </ul>
                    </div>
                  </div>
                </swiper-slide>

                <swiper-slide v-if="isKb">
                  <div class="swipe-item">
                    <div class="type">POS点餐</div>
                    <div class="ts-content">
                      <div class="top">
                        <div class="total-get">
                          <span>实收金额(元)</span>
                          <div>{{trafficStatistics[6].todayPosAmt}}</div>
                        </div>
                        <div class="discount">优惠金额：{{trafficStatistics[6].todayPosDiscountAmt}}</div>
                      </div>
                      <ul class="bottom">
                        <li>
                          <div class="money">
                            <span>订单金额(元)</span>
                            <div>{{trafficStatistics[6].todayPosOrderAmt}}</div>
                          </div>
                          <div class="amount">订单笔数(笔)：{{trafficStatistics[6].todayPosOrderCnt}}</div>
                        </li>
                        <li>
                          <div class="money">
                            <span>退款金额(元)</span>
                            <div>{{trafficStatistics[6].todayPosRefAmt}}</div>
                          </div>
                          <div class="amount">退款笔数(笔)：{{trafficStatistics[6].todayPosRefCnt}}</div>
                        </li>
                      </ul>
                    </div>
                  </div>
                </swiper-slide>

                <swiper-slide v-if="isKb">
                  <div class="swipe-item">
                    <div class="type">桌边付</div>
                    <div class="ts-content">
                      <div class="top">
                        <div class="total-get">
                          <span>实收金额(元)</span>
                          <div>{{trafficStatistics[7].todayZbfAmt}}</div>
                        </div>
                        <div class="discount">优惠金额：{{trafficStatistics[7].todayZbfDiscountAmt}}</div>
                      </div>
                      <ul class="bottom">
                        <li>
                          <div class="money">
                            <span>订单金额(元)</span>
                            <div>{{trafficStatistics[7].todayZbfOrderAmt}}</div>
                          </div>
                          <div class="amount">订单笔数(笔)：{{trafficStatistics[7].todayZbfOrderCnt}}</div>
                        </li>
                        <li>
                          <div class="money">
                            <span>退款金额(元)</span>
                            <div>{{trafficStatistics[7].todayZbfRefAmt}}</div>
                          </div>
                          <div class="amount">退款笔数(笔)：{{trafficStatistics[7].todayZbfRefCnt}}</div>
                        </li>
                      </ul>
                    </div>
                  </div>
                </swiper-slide>

                <swiper-slide v-if="isWm">
                  <div class="swipe-item">
                    <div class="type">
                      饿了么外卖
                      <InfoModal infoTitle="说明" :infoText="['外卖业务的订单金额：含订单金额+打包费+配送费']" />
                    </div>
                    <div class="ts-content">
                      <div class="top">
                        <div class="total-get">
                          <span>用户实付</span>
                          <div>{{trafficStatistics[8].todayElmPayAmt}}</div>
                        </div>
                        <div class="discount">优惠金额：{{trafficStatistics[8].todayElmDisAmt}}</div>
                      </div>
                      <ul class="bottom">
                        <li>
                          <div class="money">
                            <span>订单金额(元)</span>
                            <div>{{trafficStatistics[8].todayElmOrderAmt}}</div>
                          </div>
                        </li>
                        <li>
                          <div class="money">
                            <span>订单笔数(笔)</span>
                            <div>{{trafficStatistics[8].todayElmOrderCnt}}</div>
                          </div>
                        </li>
                      </ul>
                      <p class="tip">数据来自第三方平台会有偏差，仅供参考</p>
                    </div>
                  </div>
                </swiper-slide>
                <swiper-slide v-if="isWm">
                  <div class="swipe-item">
                    <div class="type">
                      美团外卖
                      <InfoModal infoTitle="说明" :infoText="['外卖业务的订单金额：含订单金额+打包费+配送费']" />
                    </div>
                    <div class="ts-content">
                      <div class="top">
                        <div class="total-get">
                          <span>用户实付</span>
                          <div>{{trafficStatistics[8].todayMtPayAmt}}</div>
                        </div>
                        <div class="discount">优惠金额：{{trafficStatistics[8].todayMtDisAmt}}</div>
                      </div>
                      <ul class="bottom">
                        <li>
                          <div class="money">
                            <span>订单金额(元)</span>
                            <div>{{trafficStatistics[8].todayMtOrderAmt}}</div>
                          </div>
                        </li>
                        <li>
                          <div class="money">
                            <span>订单笔数(笔)</span>
                            <div>{{trafficStatistics[8].todayMtOrderCnt}}</div>
                          </div>
                        </li>
                      </ul>
                      <p class="tip">数据来自第三方平台会有偏差，仅供参考</p>
                    </div>
                  </div>
                </swiper-slide>
                <div class="swiper-pagination" style="bottom:0;" slot="pagination"></div>
              </swiper>
            </div>
          </div>
          <div class="zhk-statistics" v-if="dateFlag!='1'">
            <div class="section-title">
              收入趋势
              <InfoModal
                infoTitle="指标说明"
                :infoText="['实收金额：指自己的实际资金收入，包含销售收入和会员卡储值收入','订单金额：指销售订单中，订单的应收金额，即交易金额']"
              />
            </div>
            <div class="section-container">
              <ul class="tab-bar">
                <li
                  class="checked"
                  :key="index"
                  v-for="(item,index) in tabCompent2.tabList"
                  @click="toggleTab(tabCompent2,index)"
                  :class="{selected:index == tabCompent2.tabIndex}"
                >{{item}}</li>
              </ul>
            </div>
            <div class="section chart-wrap" v-if="0 == tabCompent2.tabIndex">
              <ve-line :data="chartData2"></ve-line>
            </div>
            <div class="section chart-wrap" v-if="1 == tabCompent2.tabIndex">
              <ve-line :data="chartData4"></ve-line>
            </div>
          </div>
          <div class="zhk-statistics" v-if="dateFlag!='1'">
            <div class="section-title">
              订单与笔单价
              <InfoModal
                infoTitle="指标说明"
                :ctUnli="'观察数据变化可以判断各种营销活动和经营策略的实际效果'"
                :infoText="['消费订单笔数：顾客消费订单的笔数，不包含储值订单','笔单价=消费订单金额 / 消费订单笔数']"
              />
            </div>
            <div class="section chart-wrap">
              <ve-histogram :data="chartData3" :settings="chartSettings2"></ve-histogram>
            </div>
          </div>
          <div class="store" v-if="shopId=='all' && shopNum>1">
            <div class="section-title">
              门店对比
              <InfoModal
                infoTitle="指标说明"
                :ctUnli="'对比分析门店交易表现，以便对各门店的运营进行策略调整。'"
                :infoText="['实收金额：门店的实际收入总金额，包括消费订单收入（去除使用会员储值卡支付的金额）和储值卡充值收入','消费订单金额：顾客在门店消费产生的总订单金额','消费订单笔单价：门店平均每笔订单的金额']"
              />
            </div>
            <div class="store-compare-component">
              <div class="section-container">
                <ul class="tab-bar">
                  <li
                    class="checked"
                    :key="index"
                    v-for="(item,index) in tabCompent3.tabList"
                    @click="toggleTab(tabCompent3,index)"
                    :class="{selected:index == tabCompent3.tabIndex}"
                  >{{item}}</li>
                </ul>
              </div>
              <div class="scroll-container">
                <div class="section" :class="{hide:0 != tabCompent3.tabIndex}">
                  <ul class="table">
                    <li>
                      <div>序号</div>
                      <div>门店</div>
                      <div>实收金额(元)</div>
                      <div>占比(%)</div>
                    </li>
                  </ul>
                  <div class="scroll-wrap">
                    <ul class="table">
                      <li v-for="(item,index) in storeDataList" :key="item.id">
                        <div>{{ index+1 }}</div>
                        <div>{{ item.name }}</div>
                        <div>{{ item.receiveMoney }}</div>
                        <div>{{ item.receiveProportion }}</div>
                      </li>
                    </ul>
                  </div>
                </div>
                <div class="section" :class="{hide:1 != tabCompent3.tabIndex}">
                  <ul class="table">
                    <li>
                      <div>序号</div>
                      <div>门店</div>
                      <div>订单金额(元)</div>
                      <div>占比(%)</div>
                    </li>
                  </ul>
                  <div class="scroll-wrap">
                    <ul class="table">
                      <li v-for="(item,index) in storeDataList" :key="item.id">
                        <div>{{ index+1 }}</div>
                        <div>{{ item.name }}</div>
                        <div>{{ item.orderPrice }}</div>
                        <div>{{ item.orderPriceProportion }}</div>
                      </li>
                    </ul>
                  </div>
                </div>
                <div class="section" :class="{hide:2 != tabCompent3.tabIndex}">
                  <ul class="table">
                    <li>
                      <div>序号</div>
                      <div>门店</div>
                      <div>笔单价(元)</div>
                    </li>
                  </ul>
                  <div class="scroll-wrap">
                    <ul class="table">
                      <li v-for="(item,index) in storeDataList" :key="item.id">
                        <div>{{ index+1 }}</div>
                        <div>{{ item.name }}</div>
                        <div>{{ item.unitPrice }}</div>
                      </li>
                    </ul>
                  </div>
                </div>
              </div>
            </div>
            <div v-show="!storeDataList.length" class="no-more">
                <span>暂无数据</span>
            </div>
            <a class="all-store" @click="allStore">
              <span>查看全部门店</span>
              <i class="zhk-list_rarrow"></i>
            </a>
          </div>
        </v-loadmore>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import { Toast } from "mint-ui";
import config from "../../base/profile/config.json";
import jsBridge from "../../tools/jsBridge.js";
import customHeader from "../../components/header/header";
import StoreChoice from "../../components/StoreChoice/StoreChoice";
import DateChoice from "../../components/DateChoice/DateChoice";
import calendarDay from "../../components/calendar/calendarDay";
import calendarWeek from "../../components/calendar/calendarWeek";
import calendarMonth from "../../components/calendar/calendarMonth";
import moment from "moment";
import menuList from "../../components/menuList/menuList";
import InfoModal from "../../components/InfoModal/InfoModal";
import storeCompare from "../storeCompare/storeCompare";
import orderSource from "../storeCompare/orderSource";
import { Popup, Loadmore } from "mint-ui";
import 'swiper/dist/css/swiper.css'
import { swiper, swiperSlide } from 'vue-awesome-swiper'
Vue.component(Popup.name, Popup);
export default {
  name: "businessAnalysis",
  data() {
    this.chartSettings = {
      dimension: 'type',
      metrics: 'amount',
      radius: 80,
      label: {
        formatter: '{b}\n{c}\n({d}%)',
        //fontSize:10,
      },
      //labelLine:{
      //show:false
      //length2:20
      //}
    };
    this.chartSettings2 = {
      showLine: ["笔单价(元)"]
    };
    this.pieColors= ['#5BB1EF','#19D5AE','#F05151', '#1298A1', '#F59145',"#9E36C4"];
    return {
      moment: moment,
      menuList: [{ label: "日报", value: "day" }, { label: "周报", value: "week" }, { label: "月报", value: "month" }, { label: "自定义", value: "custom" }],
      menuBtnBottom: 0,
      storeVisible: false,
      swiperOption: {
        pagination: {
          el: '.swiper-pagination',
          clickable: true
        }
      },
      topStatus: "",


      shopId: "all",
      shopName: "",
      storeName: '',
      role: false,
      roleData: null,
      isKb: false,
      isWm: false,
      shopNum: 0,
      startDate: moment().startOf('day').valueOf(),
      endDate: moment().startOf('day').valueOf(),
      dateFlag: "1",//1 今日 2 昨日 3近七天 4近30天 5 近90天 0 自定义时间
      dateLabel: '今天',
      filterData: {
        isIndexPage: true,
        startDate: moment().startOf('day').valueOf(),
        endDate: moment().startOf('day').valueOf()
      },
      tradeSum: {},//交易汇总
      trafficStatistics: [{ todayReceiveAmt: 0.00, todayReceiveOrderAmt: 0.00, todayReceiveOrderCnt: 0, todayReceiveDiscountAmt: 0.00, todayReceiveRefAmt: 0.00, todayReceiveRefCnt: 0 },//收银
      { todayOnlineGoodsUseAmt: 0.00, onlineGoodsTakenCnt: 0, onlineGoodsUseCnt: 0, onlineGoodsNoUseCnt: 0, onlineGoodsExpIncome: 0.00 },//在线商品
      { todayCardRechargeAmt: 0.00, todayCardRecOrderAmt: 0.00, todayCardRecCnt: 0, todayCardRecDisAmt: 0.00 },//会员卡储值
      { todayCardConsAmt: 0.00, todayCardConsOrderAmt: 0.00, todayCardConsOrderCnt: 0, todayCardConsDisAmt: 0.00, todayCardConsRefAmt: 0.00, todayCardConsRefCnt: 0 },//会员卡消费
      { todayScanAmt: 0.00, todayScanOrderAmt: 0.00, todayScanOrderCnt: 0, todayScanDiscountAmt: 0.00, todayScanRefAmt: 0.00, todayScanRefCnt: 0 },//扫码点餐
      { todayAppointAmt: 0.00, todayAppointOrderAmt: 0.00, todayAppointOrderCnt: 0, todayAppointDiscountAmt: 0.00, todayAppointRefAmt: 0.00, todayAppointRefundCnt: 0 },//口碑点餐
      { todayPosAmt: 0.00, todayPosOrderAmt: 0.00, todayPosOrderCnt: 0, todayPosDiscountAmt: 0.00, todayPosRefAmt: 0.00, todayPosRefCnt: 0 },//Pos
      { todayZbfAmt: 0.00, todayZbfOrderAmt: 0.00, todayZbfOrderCnt: 0, todayZbfDiscountAmt: 0.00, todayZbfRefAmt: 0.00, todayZbfRefCnt: 0 },//桌边付
      { todayElmPayAmt: 0.00, todayElmPackageAmt: 0.00, todayElmDistbAmt: 0.00, todayElmOrderAmt: 0.00, todayElmOrderCnt: 0, todayElmDisAmt: 0.00, todayMtPayAmt: 0.00, todayMtPkgAmt: 0.00, todayMtDistbAmt: 0.00, todayMtOrderAmt: 0.00, todayMtOrderCnt: 0, todayMtDisAmt: 0.00 }],//业务统计
      tabCompent: { tabList: ["支付方式", "收款渠道"], tabIndex: 0 },
      tabCompent2: { tabList: ["实收金额", "订单金额"], tabIndex: 0 },
      tabCompent3: { tabList: ["实收金额", "订单金额", "笔单价"], tabIndex: 0 },
      tabCompent4: { tabList: ["收银员", "收款码", "设备"], tabIndex: 0 },
      dataList: [

      ],
      chartData: {
        columns: ["type", "amount"],
        rows: [
        ]
      },
      chartData1: {
        columns: ["type", "amount"],
        rows: [

        ]
      },
      chartData2: {
        columns: ["日期", "实收金额"],
        rows: [

        ]
      },
      chartData4: {
        columns: ["日期", "订单金额"],
        rows: [

        ]
      },
      chartData3: {
        columns: ["日期", "消费订单笔数(笔)", "笔单价(元)"],
        rows: [

        ]
      },
      reportFilter: {
        reportType: "day",
        dateLabel: ""
      },
      orderSource: [],
      storeDataList: [],
      dayPreDisabled:false,
      dayNextDisabled:true,
      weekPreDisabled:false,
      weekNextDisabled:true,
      monthPreDisabled:false,
	  monthNextDisabled:true,
    calendarRange:[],
    calendarIndex:[0,0],
    CommonUtil:CommonUtil,
    errCount:0,//汇总接口调用失败次数
    errTimer:null,
    orderSourceTab:{index:0,type:2},
    orderSourceTotalCount:0,
    };
  },
  methods: {
    bindNewOrderEvent() {
      jsBridge.addNewOrderEventListener(() => {
        if (this.dateFlag == "1") {
          CommonUtil.getRoleInfo().then(data => {
            this.setRoleInfo(data);
            this.getSumData();
          });
        }
      });
    },
    handleTopChange(status) {
      this.topStatus = status;
    },
    handleMenu(v) {
      if (v == "day") {
        this.$refs.calendarDay.popupShow();
        this.$refs.calendarWeek.popupHide();
        this.$refs.calendarMonth.popupHide();
        this.$refs.DateChoice.back();
      } else if (v == "week") {
        this.$refs.calendarDay.popupHide();
        this.$refs.calendarWeek.popupShow();
        this.$refs.calendarMonth.popupHide();
        this.$refs.DateChoice.back();
      } else if (v == "month") {
        this.$refs.calendarDay.popupHide();
        this.$refs.calendarWeek.popupHide();
        this.$refs.calendarMonth.popupShow();
        this.$refs.DateChoice.back();
      } else if (v == "custom") {
        this.$refs.calendarDay.popupHide();
        this.$refs.calendarWeek.popupHide();
        this.$refs.calendarMonth.popupHide();
        this.$refs.DateChoice.popupShow();
      }
    },
    toggleMenu() {
      if (this.$refs.menuList.visible) {
        this.$refs.menuList.hide();
      } else {
        this.$refs.menuList.show();
      }
    },
    loadTop() {
      CommonUtil.getRoleInfo().then(data => {
        this.setRoleInfo(data);
        this.reqAll();
      });

    },
    storeNameFormate() {
      if (this.storeName) {
        return this.storeName;
      } else {
        return "全部门店";
      }
    },
    handleClickSelectStore() {
      if (this.role) {
        this.$refs.StoreChoice.popupShow();
        this.storeVisible = true;
      }
    },
    handleClickSelectDate() {
      this.$refs.DateChoice.popupVisible = true;
    },
    formatDate(strTime) {
      if (strTime != null && strTime != "") {
        var date = new Date(strTime);
        var year = date.getFullYear();//取得年
        var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;    //取得月,js从0开始取,所以+1
        var date1 = date.getDate() < 10 ? "0" + (date.getDate()) : date.getDate(); //取得天
        return year + "" + month + "" + date1;
      } else {
        return "";
      }
    },
    toggleTab(tabCompent, index) {
      tabCompent.tabIndex = index;

      if (tabCompent.tabList[0] == "收银员") {
        let type = 2;
        if (index === 0) {
          type = 2;
        } else if (index === 1) {
          type = 3;
        } else if (index === 2) {
          type = 1;
        }
        this.orderSourceTab={index:index,type:type};
        this.getOrderSource();
      }
       if (tabCompent.tabList[2] == "笔单价") {
         this.storeDataSort();
      }
    },
    getSelectStoreValue(value, storeName) {
      var shopId = value[0].selectKey;
      this.shopId = shopId;
      this.storeName = storeName;
      this.filterData.shopIds = shopId;
      this.reqAll();
    },
    getSelectDateValue(value, dateLabel,index) {
      this.reportFilter.reportType = "custom";
      this.reportFilter.dateLabel = moment(value.startDate).format("YYYY-MM-DD") + " 至 " + moment(value.endDate).format("YYYY-MM-DD");
      this.startDate = value.startDate.getTime();
      this.endDate = value.endDate.getTime();
      this.dateLabel = dateLabel;
      this.dateFlag = value.selectRadio;


      // this.getSumData();
      // this.getOrderSource();
      //if(value.selectRadio!="1"){
      // this.getIncomeData();
      // this.getOrderData();


      //}
      this.filterData = { startDate: this.startDate, endDate: this.endDate, dateFlag: this.dateFlag, isIndexPage: true };
      this.reqAll();
	},
	handleRangeMin(obj){
	  this.calendarRange.push(obj);
	},
    handleDateChange(dateType,btnType){
      const s=this.startDate;
      if(dateType=="day"){
        if(btnType=="pre"){

          if(moment(s).startOf('days')<=moment().subtract(5, 'months').startOf('months')){//当前日期为6个月前
            return;
          }
          this.dayNextDisabled=false;
		      let af= moment(s).subtract(1, 'days').valueOf();
          this.startDate=af;
          this.endDate=af;
          let today=af==moment().startOf('day').valueOf()?"(今天)":"";
          this.reportFilter={reportType: "day",dateLabel:moment(af).format("YYYY-MM-DD")+today };

          if(moment(af).startOf('day')<=moment().subtract(5, 'months').startOf('months')){
            this.dayPreDisabled=true;
          }else{
            this.dayPreDisabled=false;
          }
          // return;
        }

      }
      if(dateType=="day"){
        if(btnType=="next"){

          if(moment(s).startOf('day')>=moment().startOf('day')){//当天
            return;
          }
          this.dayPreDisabled=false;
		      let af= moment(s).add(1, 'days').valueOf();
          this.startDate=af;
          this.endDate=af;
          let today=af==moment().startOf('day').valueOf()?"(今天)":"";
          this.reportFilter={reportType: "day",dateLabel:moment(af).format("YYYY-MM-DD")+today };

          if(moment(af).startOf('day')>=moment().startOf('day')){
            this.dayNextDisabled=true;
          }else{
            this.dayNextDisabled=false;
          }
         // return;
        }

      }
      if(dateType=="month"){
        if(btnType=="pre"){
		      const monthMin=this.calendarRange.filter(item=>{return item.reportType=="month"})[0].value;
          if(s<=monthMin){
            return;
          }
          const start= moment(s).subtract(1, 'months').startOf('month').valueOf();
          const end= moment(s).subtract(1, 'months').endOf('month').valueOf();
          this.monthNextDisabled=false;
          this.startDate=start;
          this.endDate=end;
          this.reportFilter={reportType: "month",dateLabel: moment(start).format("YYYY年MM月") };

          if(start<=monthMin){
            this.monthPreDisabled=true;
          }else{
            this.monthPreDisabled=false;
          }
          //return;
        }

      }
      if(dateType=="month"){
        if(btnType=="next"){


          if(moment(s).startOf('month')>=moment().startOf('month')){//当前月
            return;
          }

          const start= moment(s).add(1, 'months').startOf('month').valueOf();
          const end= moment(s).add(1, 'months').endOf('month').valueOf();

          this.monthPreDisabled=false;
          this.startDate=start;
          this.endDate=end;
          this.reportFilter={reportType: "month",dateLabel: moment(start).format("YYYY年MM月") };
           if(moment(start).startOf('month')>=moment().startOf('month')){//当前月
            this.monthNextDisabled=true;
          }else{
            this.monthNextDisabled=false;
          }
           //return;
        }

      }

      if(dateType=="week"){
        if(btnType=="pre"){
          const weekList=this.calendarRange.filter(item=>{return item.reportType=="week"})[0].value;
          if(JSON.stringify(this.calendarIndex)=="[0,0]"){
            return;
          }

          let index0=this.calendarIndex[0];
          let index1=this.calendarIndex[1]-1;
          if(index1<0){
            index0=this.calendarIndex[0]-1;
            index1=weekList[index0].weeks.length-1;
          }
          this.calendarIndex=[index0,index1];

          const wpyear=weekList[this.calendarIndex[0]].year;
          const wpmonth=weekList[this.calendarIndex[0]].month;
          const wpweek= weekList[this.calendarIndex[0]].weeks[this.calendarIndex[1]];


          let dayArr = wpweek.day.split("-");

          const wpstart = new Date(`${wpyear}/${dayArr[0].split(".")[0]}/${dayArr[0].split(".")[1]}`);
          const wpend = new Date(`${wpyear}/${dayArr[1].split(".")[0]}/${dayArr[1].split(".")[1]}`);


          this.weekNextDisabled=false;
          this.startDate=wpstart.getTime();
          this.endDate=wpend.getTime();
          this.reportFilter={reportType: "week",dateLabel: `${wpyear}年${wpmonth}月 第${wpweek.week}周 ${wpweek.day}` };

          if(JSON.stringify(this.calendarIndex)=="[0,0]"){
            this.weekPreDisabled=true;
          }else{
            this.weekPreDisabled=false;
          }
          //return;
        }

      }
      if(dateType=="week"){
        if(btnType=="next"){
          const weekList=this.calendarRange.filter(item=>{return item.reportType=="week"})[0].value;
          if(JSON.stringify(this.calendarIndex)==JSON.stringify([weekList.length-1,weekList[weekList.length-1].weeks.length-1])){
            return;
          }

          let index0=this.calendarIndex[0];
          let index1=this.calendarIndex[1]+1;
          if(index1>weekList[index0].weeks.length-1){
            index0=this.calendarIndex[0]+1;
            index1=0;
          }
          this.calendarIndex=[index0,index1];

          const wnyear=weekList[this.calendarIndex[0]].year;
          const wnmonth=weekList[this.calendarIndex[0]].month;
          const wnweek= weekList[this.calendarIndex[0]].weeks[this.calendarIndex[1]];


          let dayArr = wnweek.day.split("-");

          const wnstart = new Date(`${wnyear}/${dayArr[0].split(".")[0]}/${dayArr[0].split(".")[1]}`);
          const wnend = new Date(`${wnyear}/${dayArr[1].split(".")[0]}/${dayArr[1].split(".")[1]}`);


          this.weekPreDisabled=false;
          this.startDate=wnstart.getTime();
          this.endDate=wnend.getTime();
          this.reportFilter={reportType: "week",dateLabel: `${wnyear}年${wnmonth}月 第${wnweek.week}周 ${wnweek.day}` };

         if(JSON.stringify(this.calendarIndex)==JSON.stringify([weekList.length-1,weekList[weekList.length-1].weeks.length-1])){
            this.weekNextDisabled=true;
          }else{
            this.weekNextDisabled=false;
          }
          //return;
        }

      }
      this.filterData = { startDate: this.startDate, endDate: this.endDate, isIndexPage: true, dateLabel: this.dateLabel, shopIds: this.shopId };
    //  let ss= moment(this.startDate).format("YYYY年MM月DD HH")
    //  let ee= moment(this.endDate).format("YYYY年MM月DD HH")
      this.reqAll();

    },
    checkUserRole() {
      CommonUtil.getRoleInfo().then(data => {
        this.setRoleInfo(data);
        this.reqAll();
      });
    },
    setRoleInfo(data) {
      if (this.roleData) {
        return;
      }
      if (data != null && JSON.stringify(data) != '{}') {
        this.roleData = data;
        const shopId = data.selfShopId;
        const shopName = data.selfShopName;
        if (shopId != null && shopId != "all" && shopName != "") {
          this.role = false;
          this.shopId = shopId;
          this.shopName = shopName;
        } else {
          this.role = true;
        }
        this.isKb = data.isKb;
        this.isWm = data.isWm;
        this.shopNum = data.shopNum;
      }
    },
    getSumData(callBack) {
      var shopId = this.shopId;
      var startDate = this.startDate;
      var endDate = this.endDate;
      var dateFlag = this.dateFlag;

      // var tradeSum = {        todayAmt: null,//实收总金额
      //   todayOrderAmt: null,//订单订单金额
      //   todayOrderCnt: null,//订单数量
      //   todaySupplierDiscount: null,//商家优惠
      //   todayRefundAmt: null,//退款金额
      //   todayRefundCnt: null      };//退款笔数
      var tradeSum = this.tradeSum;
      var trafficDis = {        todayAmt: 0.00,//实收总金额
        todayReceiveAmt: 0.00,//收银实收金额
        todayOnlineGoodsUseAmt: 0.00,//在线商品核销实收金额
        todayAppointAmt: 0.00,//口碑点餐实收金额
        todayScanAmt: 0.00,//扫码点餐实收金额
        todayPosAmt: 0.00,//Pos点餐实收金额
        todayZbfAmt: 0.00,//桌边付实收金额
        todayCardRechargeAmt: 0.00,//会员卡储值实收金额
        todayTakeoutAmt: 0.00      };//外卖实收金额
      var payMent = {        todayAmt: 0.00,//实收总金额
        todayAlipayAmt: 0.00,//支付宝支付金额
        todayWechatpayAmt: 0.00,//微信支付金额
        todayCashpayAmt: 0.00,//现金支付金额
        todayUnionpayAmt: 0.00,//银联支付金额
        todayCloudFlashPayAmt: 0.00,//云闪付支付金额
        todayOtherpayAmt: 0.00      }//其他支付方式金额（外卖）
      var trafficStatistics = [{ todayReceiveAmt: 0.00, todayReceiveOrderAmt: 0.00, todayReceiveOrderCnt: 0, todayReceiveDiscountAmt: 0.00, todayReceiveRefAmt: 0.00, todayReceiveRefCnt: 0 },//收银
      { todayOnlineGoodsUseAmt: 0.00, onlineGoodsTakenCnt: 0, onlineGoodsUseCnt: 0, onlineGoodsNoUseCnt: 0, onlineGoodsExpIncome: 0.00 },//在线商品
      { todayCardRechargeAmt: 0.00, todayCardRecOrderAmt: 0.00, todayCardRecCnt: 0, todayCardRecDisAmt: 0.00 },//会员卡储值
      { todayCardConsAmt: 0.00, todayCardConsOrderAmt: 0.00, todayCardConsOrderCnt: 0, todayCardConsDisAmt: 0.00, todayCardConsRefAmt: 0.00, todayCardConsRefCnt: 0 },//会员卡消费
      { todayScanAmt: 0.00, todayScanOrderAmt: 0.00, todayScanOrderCnt: 0, todayScanDiscountAmt: 0.00, todayScanRefAmt: 0.00, todayScanRefCnt: 0 },//扫码点餐
      { todayAppointAmt: 0.00, todayAppointOrderAmt: 0.00, todayAppointOrderCnt: 0, todayAppointDiscountAmt: 0.00, todayAppointRefAmt: 0.00, todayAppointRefundCnt: 0 },//口碑点餐
      { todayPosAmt: 0.00, todayPosOrderAmt: 0.00, todayPosOrderCnt: 0, todayPosDiscountAmt: 0.00, todayPosRefAmt: 0.00, todayPosRefCnt: 0 },//Pos
      { todayZbfAmt: 0.00, todayZbfOrderAmt: 0.00, todayZbfOrderCnt: 0, todayZbfDiscountAmt: 0.00, todayZbfRefAmt: 0.00, todayZbfRefCnt: 0 },//桌边付
      { todayElmPayAmt: 0.00, todayElmPackageAmt: 0.00, todayElmDistbAmt: 0.00, todayElmOrderAmt: 0.00, todayElmOrderCnt: 0, todayElmDisAmt: 0.00, todayMtPayAmt: 0.00, todayMtPkgAmt: 0.00, todayMtDistbAmt: 0.00, todayMtOrderAmt: 0.00, todayMtOrderCnt: 0, todayMtDisAmt: 0.00 }];

      let param = { startDate: startDate, endDate: endDate };
      if (shopId != "all") {
        param.shopIds = [shopId];
      }
      this.ajax({
        url:'/newapp/statistics/queryShopBusinessDataForCloudPay.do',
        type: 'post',
        data: param,
        controlLoading: true,
      }).then((res) => {
        callBack&&callBack();
        if (res.success && res.resultObject != null) {
          this.errCount=0;
          this.errTimer=null;
          window.clearTimeout(this.errTimer);
          var model = res.resultObject;
          tradeSum = {            todayAmt: model.todayAmt == null ? 0.00 : model.todayAmt,
            todayOrderAmt: model.todayOrderAmt == null ? 0.00 : model.todayOrderAmt,
            todayOrderCnt: model.todayOrderCnt == null ? 0 : model.todayOrderCnt,
            todaySupplierDiscount: model.todaySupplierDiscount == null ? 0.00 : model.todaySupplierDiscount,
            todayRefundAmt: model.todayRefundAmt == null ? 0.00 : model.todayRefundAmt,
            todayRefundCnt: model.todayRefundCnt == null ? 0 : model.todayRefundCnt          };
          trafficDis = {            todayAmt: model.todayAmt,
            todayReceiveAmt: model.todayReceiveAmt,
            todayOnlineGoodsUseAmt: model.todayOnlineGoodsUseAmt,
            todayAppointAmt: model.todayAppointAmt,
            todayScanAmt: model.todayScanAmt,
            todayPosAmt: model.todayPosAmt,
            todayZbfAmt: model.todayZbfAmt,
            todayCardRechargeAmt: model.todayCardRechargeAmt,
            todayTakeoutAmt: model.todayTakeoutAmt          };
          payMent = {            todayAmt: model.todayAmt,
            todayAlipayAmt: model.todayAlipayAmt,
            todayWechatpayAmt: model.todayWechatpayAmt,
            todayCashpayAmt: model.todayCashpayAmt,
            todayUnionpayAmt: model.todayUnionpayAmt,
            todayCloudFlashPayAmt: model.todayCloudFlashPayAmt,
            todayOtherpayAmt: model.todayOtherpayAmt          };
          trafficStatistics = [
            {              todayReceiveAmt: model.todayReceiveAmt,
              todayReceiveOrderAmt: model.todayReceiveOrderAmt,
              todayReceiveOrderCnt: model.todayReceiveOrderCnt,
              todayReceiveDiscountAmt: model.todayReceiveDiscountAmt,
              todayReceiveRefAmt: model.todayReceiveRefAmt,
              todayReceiveRefCnt: model.todayReceiveRefCnt},//收银
            {              todayOnlineGoodsUseAmt: model.todayOnlineGoodsUseAmt == null ? 0.00 : model.todayOnlineGoodsUseAmt,
              onlineGoodsTakenCnt: model.onlineGoodsTakenCnt == null ? 0 : model.onlineGoodsTakenCnt,
              onlineGoodsUseCnt: model.onlineGoodsUseCnt == null ? 0 : model.onlineGoodsUseCnt,
              onlineGoodsNoUseCnt: model.onlineGoodsNoUseCnt == null ? 0 : model.onlineGoodsNoUseCnt,
              onlineGoodsExpIncome: model.onlineGoodsExpIncome == null ? 0.00 : model.onlineGoodsExpIncome            },//在线商品
            {              todayCardRechargeAmt: model.todayCardRechargeAmt == null ? 0.00 : model.todayCardRechargeAmt,
              todayCardRecOrderAmt: model.todayCardRecOrderAmt == null ? 0.00 : model.todayCardRecOrderAmt,
              todayCardRecCnt: model.todayCardRecCnt == null ? 0 : model.todayCardRecCnt,
              todayCardRecDisAmt: model.todayCardRecDisAmt == null ? 0.00 : model.todayCardRecDisAmt            },//会员卡储值
            {              todayCardConsAmt: model.todayCardConsAmt == null ? 0.00 : model.todayCardConsAmt,
              todayCardConsOrderAmt: model.todayCardConsOrderAmt == null ? 0.00 : model.todayCardConsOrderAmt,
              todayCardConsOrderCnt: model.todayCardConsOrderCnt == null ? 0 : model.todayCardConsOrderCnt,
              todayCardConsDisAmt: model.todayCardConsDisAmt == null ? 0.00 : model.todayCardConsDisAmt,
              todayCardConsRefAmt: model.todayCardConsRefAmt == null ? 0.00 : model.todayCardConsRefAmt,
              todayCardConsRefCnt: model.todayCardConsRefCnt == null ? 0 : model.todayCardConsRefCnt            },//会员卡消费
            {              todayScanAmt: model.todayScanAmt == null ? 0.00 : model.todayScanAmt,
              todayScanOrderAmt: model.todayScanOrderAmt == null ? 0.00 : model.todayScanOrderAmt,
              todayScanOrderCnt: model.todayScanOrderCnt == null ? 0 : model.todayScanOrderCnt,
              todayScanDiscountAmt: model.todayScanDiscountAmt == null ? 0.00 : model.todayScanDiscountAmt,
              todayScanRefAmt: model.todayScanRefAmt == null ? 0.00 : model.todayScanRefAmt,
              todayScanRefCnt: model.todayScanRefCnt == null ? 0 : model.todayScanRefCnt            },//扫码点餐
            {              todayAppointAmt: model.todayAppointAmt == null ? 0.00 : model.todayAppointAmt,
              todayAppointOrderAmt: model.todayAppointOrderAmt == null ? 0.00 : model.todayAppointOrderAmt,
              todayAppointOrderCnt: model.todayAppointOrderCnt == null ? 0 : model.todayAppointOrderCnt,
              todayAppointDiscountAmt: model.todayAppointDiscountAmt == null ? 0.00 : model.todayAppointDiscountAmt,
              todayAppointRefAmt: model.todayAppointRefAmt == null ? 0.00 : model.todayAppointRefAmt,
              todayAppointRefundCnt: model.todayAppointRefundCnt == null ? 0 : model.todayAppointRefundCnt            },//口碑点餐
            {              todayPosAmt: model.todayPosAmt == null ? 0.00 : model.todayPosAmt,
              todayPosOrderAmt: model.todayPosOrderAmt == null ? 0.00 : model.todayPosOrderAmt,
              todayPosOrderCnt: model.todayPosOrderCnt == null ? 0 : model.todayPosOrderCnt,
              todayPosDiscountAmt: model.todayPosDiscountAmt == null ? 0.00 : model.todayPosDiscountAmt,
              todayPosRefAmt: model.todayPosRefAmt == null ? 0.00 : model.todayPosRefAmt,
              todayPosRefCnt: model.todayPosRefCnt == null ? 0 : model.todayPosRefCnt            },//Pos
            {              todayZbfAmt: model.todayZbfAmt == null ? 0.00 : model.todayZbfAmt,
              todayZbfOrderAmt: model.todayZbfOrderAmt == null ? 0.00 : model.todayZbfOrderAmt,
              todayZbfOrderCnt: model.todayZbfOrderCnt == null ? 0 : model.todayZbfOrderCnt,
              todayZbfDiscountAmt: model.todayZbfDiscountAmt == null ? 0.00 : model.todayZbfDiscountAmt,
              todayZbfRefAmt: model.todayZbfRefAmt == null ? 0.00 : model.todayZbfRefAmt,
              todayZbfRefCnt: model.todayZbfRefCnt == null ? 0 : model.todayZbfRefCnt            },//桌边付
            {              todayElmPayAmt: model.todayElmPayAmt == null ? 0.00 : model.todayElmPayAmt,
              todayElmPackageAmt: model.todayElmPackageAmt == null ? 0.00 : model.todayElmPackageAmt,
              todayElmDistbAmt: model.todayElmDistbAmt == null ? 0.00 : model.todayElmDistbAmt,
              todayElmOrderAmt: model.todayElmOrderAmt == null ? 0.00 : model.todayElmOrderAmt,
              todayElmOrderCnt: model.todayElmOrderCnt == null ? 0 : model.todayElmOrderCnt,
              todayElmDisAmt: model.todayElmDisAmt == null ? 0.00 : model.todayElmDisAmt,
              todayMtPayAmt: model.todayMtPayAmt == null ? 0.00 : model.todayMtPayAmt,
              todayMtPkgAmt: model.todayMtPkgAmt == null ? 0.00 : model.todayMtPkgAmt,
              todayMtDistbAmt: model.todayMtDistbAmt == null ? 0.00 : model.todayMtDistbAmt,
              todayMtOrderAmt: model.todayMtOrderAmt == null ? 0.00 : model.todayMtOrderAmt,
              todayMtOrderCnt: model.todayMtOrderCnt == null ? 0 : model.todayMtOrderCnt,
              todayMtDisAmt: model.todayMtDisAmt == null ? 0.00 : model.todayMtDisAmt            }];

          this.changeSumData(tradeSum, trafficStatistics, payMent, trafficDis);

        }else{
          this.repeatSumData();
        }
        this.$refs.loadmore && this.$refs.loadmore.onTopLoaded && this.$refs.loadmore.onTopLoaded();
      })
        .catch((err) => {
          this.$refs.loadmore && this.$refs.loadmore.onTopLoaded && this.$refs.loadmore.onTopLoaded();
           this.repeatSumData();
        })
      this.changeSumData(tradeSum, trafficStatistics, payMent, trafficDis);
    },
    repeatSumData(){
        if(this.errCount>=3){
          this.errCount=0;
          this.errTimer=null;
          window.clearTimeout(this.errTimer);
          return;
        }
       this.errTimer=window.setTimeout(()=>{
         this.getSumData();
       },3000);
       this.errCount=this.errCount+1;
    },
    changeSumData(tradeSum, trafficStatistics, payMent, trafficDis) {
      this.tradeSum = tradeSum;
      for (var i = 0; i < trafficStatistics.length; i++) {
        Vue.set(this.trafficStatistics, i, trafficStatistics[i]);
      }
      // this.trafficStatistics = trafficStatistics;
      if (payMent.todayAmt > 0) {
        this.chartData1.rows = [
          { type: "支付宝", amount: payMent.todayAlipayAmt > 0 ? payMent.todayAlipayAmt : null },
          { type: "微信", amount: payMent.todayWechatpayAmt > 0 ? payMent.todayWechatpayAmt : null },
          { type: "云闪付", amount: payMent.todayCloudFlashPayAmt  > 0 ? payMent.todayCloudFlashPayAmt  : null },
          { type: "POS刷卡", amount: payMent.todayUnionpayAmt > 0 ? payMent.todayUnionpayAmt : null },
          { type: "现金", amount: payMent.todayCashpayAmt > 0 ? payMent.todayCashpayAmt : null },
          { type: "其他", amount: payMent.todayOtherpayAmt > 0 ? payMent.todayOtherpayAmt : null }
        ];
      } else {
        this.chartData1.rows = [
          { type: "支付宝", amount: payMent.todayAlipayAmt },
          { type: "微信", amount: payMent.todayWechatpayAmt },
          { type: "云闪付", amount: payMent.todayCloudFlashPayAmt  },
          { type: "POS刷卡", amount: payMent.todayUnionpayAmt },
          { type: "现金", amount: payMent.todayCashpayAmt },
          { type: "其他", amount: payMent.todayOtherpayAmt }
        ];
      }

      if (this.isKb) {
        if (trafficDis.todayAmt > 0) {
          this.chartData.rows = [
            { type: "收银", amount: trafficDis.todayReceiveAmt > 0 ? trafficDis.todayReceiveAmt : null },
            { type: "储值", amount: trafficDis.todayCardRechargeAmt > 0 ? trafficDis.todayCardRechargeAmt : null },
            { type: "扫码点餐", amount: trafficDis.todayScanAmt > 0 ? trafficDis.todayScanAmt : null },
            { type: "桌边付", amount: trafficDis.todayZbfAmt > 0 ? trafficDis.todayZbfAmt : null },
            { type: "商品核销", amount: trafficDis.todayOnlineGoodsUseAmt > 0 ? trafficDis.todayOnlineGoodsUseAmt : null },
            { type: "POS点餐", amount: trafficDis.todayPosAmt > 0 ? trafficDis.todayPosAmt : null },
            { type: "口碑点餐", amount: trafficDis.todayAppointAmt > 0 ? trafficDis.todayAppointAmt : null },
            { type: "外卖", amount: trafficDis.todayTakeoutAmt > 0 ? trafficDis.todayTakeoutAmt : null }
          ];
        } else {
          this.chartData.rows = [
            { type: "收银", amount: trafficDis.todayReceiveAmt },
            { type: "储值", amount: trafficDis.todayCardRechargeAmt },
            { type: "扫码点餐", amount: trafficDis.todayScanAmt },
            { type: "桌边付", amount: trafficDis.todayZbfAmt },
            { type: "商品核销", amount: trafficDis.todayOnlineGoodsUseAmt },
            { type: "POS点餐", amount: trafficDis.todayPosAmt },
            { type: "口碑点餐", amount: trafficDis.todayAppointAmt },
            { type: "外卖", amount: trafficDis.todayTakeoutAmt }
          ];
        }
      } else {
        if (this.isWm) {
          if (trafficDis.todayAmt > 0) {
            this.chartData.rows = [
              { type: "收银", amount: trafficDis.todayReceiveAmt > 0 ? trafficDis.todayReceiveAmt : null },
              { type: "外卖", amount: trafficDis.todayTakeoutAmt > 0 ? trafficDis.todayTakeoutAmt : null }
            ];
          } else {
            this.chartData.rows = [
              { type: "收银", amount: trafficDis.todayReceiveAmt },
              { type: "外卖", amount: trafficDis.todayTakeoutAmt }
            ];
          }
        } else {
          this.chartData.rows = [
            { type: "收银", amount: trafficDis.todayReceiveAmt }
          ];
        }

      }

    },
    getIncomeData() {
      var shopId = this.shopId;
      var startDate = this.startDate;
      var endDate = this.endDate;
      var dateFlag = this.dateFlag;
      var amtChart = [];
      var orderChart = [];
      this.ajax({
        url: '/newapp/statistics/queryIncomeDataNew.do?shopId=' + shopId + '&startDate=' + startDate + '&endDate=' + endDate + '&dateFlag=' + dateFlag,
        type: 'get',
        controlLoading: true,
      }).then((res) => {
        if (res.success) {
          var model = res.resultObject;
          for (var i = 0; i < model.length; i++) {
            amtChart.push({ 日期: model[i].bizDate, 实收金额: model[i].receiveAmount });
            orderChart.push({ 日期: model[i].bizDate, 订单金额: model[i].consumptionOrderAmount });
          }
          this.chartData2.rows = amtChart;
          this.chartData4.rows = orderChart;
        }
      })
        .catch((err) => {

        })
      this.chartData2.rows = amtChart;
      this.chartData4.rows = orderChart;
    },
    getOrderData() {
      var shopId = this.shopId;
      var startDate = this.startDate;
      var endDate = this.endDate;
      var dateFlag = this.dateFlag;
      var orderChart = [];
      this.ajax({
        url: '/merchantApp/businessReport/queryOrderNumberAndPerCusDataNew.do?shopId=' + shopId + '&startDate=' + startDate + '&endDate=' + endDate + '&dateFlag=' + dateFlag,
        type: 'get',
        controlLoading: true,
      }).then((res) => {
        if (res.success) {
          var model = res.resultObject;
          for (var i = 0; i < model.length; i++) {
            orderChart.push({ 日期: model[i].bizDate, "消费订单笔数(笔)": model[i].consumptionOrderPens, "笔单价(元)": model[i].penUnitPrice });
          }
          this.chartData3.rows = orderChart;
        }
      })
        .catch((err) => {

        })
      this.chartData3.rows = orderChart;
    },
    //查看全部门店
    allStore() {
      this.filterData = { startDate: this.startDate, endDate: this.endDate, dateFlag: this.dateFlag, isIndexPage: false, dateLabel: this.dateLabel,tabIndex:this.tabCompent3.tabIndex };
      this.$refs.storeCompare.popupShow();
      //this.$router.push({ path: "/businessAnalysis/storeCompare",query: { startDate:this.startDate,endDate:this.endDate,dateFlag:this.dateFlag,isIndexPage:false,dateLabel:this.dateLabel} });
    },
    //查看收款来源全部
    handleOrderSourceAll() {
      this.orderSourceParam = { startDate: this.startDate, endDate: this.endDate, shopIds: this.shopId };
      this.$refs.orderSource.popupShow();
    },
    reportSelect(data) {
      this.reportFilter = data;
      this.startDate = data.dateScope.startDate;
      this.endDate = data.dateScope.endDate;
      this.filterData = { startDate: data.dateScope.startDate, endDate: data.dateScope.endDate, isIndexPage: true, dateLabel: this.dateLabel, shopIds: this.shopId };
      this.calendarIndex=data.index;


      //前后按钮禁用判断
      if(data.reportType=="day"){
         const dayMin=this.calendarRange.filter(item=>{return item.reportType=="day"})[0].value;
        if(data.dateScope.startDate<=dayMin){
          this.dayPreDisabled=true;
          this.dayNextDisabled=false;
        }else if(data.dateScope.endDate>=moment().startOf('day').valueOf()){
          this.dayPreDisabled=false;
          this.dayNextDisabled=true;
        }else {
          this.dayPreDisabled=false;
          this.dayNextDisabled=false;
        }
      }
      if(data.reportType=="week"){
         const weekMin=this.calendarRange.filter(item=>{return item.reportType=="week"})[0].value[0];
         if(JSON.stringify(this.calendarIndex)=="[0,0]"){
          this.weekPreDisabled=true;
          this.weekNextDisabled=false;
        }else if(data.dateScope.endDate>=moment().startOf('day').valueOf()){
          this.weekPreDisabled=false;
          this.weekNextDisabled=true;
        }else {
          this.weekPreDisabled=false;
          this.weekNextDisabled=false;
        }
      }
      if(data.reportType=="month"){
         const monthMin=this.calendarRange.filter(item=>{return item.reportType=="month"})[0].value;
        if(data.dateScope.startDate<=monthMin){
          this.monthPreDisabled=true;
          this.monthNextDisabled=false;
        }else if(data.dateScope.endDate>=moment().startOf('day').valueOf()){
          this.monthPreDisabled=false;
          this.monthNextDisabled=true;
        }else {
          this.monthPreDisabled=false;
          this.monthNextDisabled=false;
        }
      }
     this.reqAll();

    },
    //收款来源
    getOrderSource() {
      const staticsType=this.orderSourceTab.type;
      //staticsType 统计类型：0 未知； 1、机具SN标识；2：收银员ID；3：收款码
      let param = { staticsType: staticsType, startDate: this.startDate, endDate: this.endDate, currentPage: 1, pageSize: 5 };
      if (this.shopId != "all") {
        param.shopIds = [this.shopId];
      }
      this.ajax({
        url: "/newapp/statistics/queryBusinessDataMoreChoise.do",
        type: "post",
        data: param,
        controlLoading: false,
      })
        .then(res => {
          if (res.success) {
            const data = res.resultObject.dataList;
            this.orderSourceTotalCount=res.resultObject.totalCount;
            this.orderSource = data.map((item)=>{
              let name="";
              if(staticsType==2){
                name= item.staticsName?`<div>${item.staticsName}</div>`:"<div>其他</div>";
              }else if(staticsType==3){
                 name= item.staticsName||item.staticsId?`<div>${item.staticsName?item.staticsName:""}<p></p>id:${item.staticsId}</div>`:"<div>其他</div>";
              }else if(staticsType==1){
                 name= item.staticsName||item.staticsId?`<div>${item.staticsName?item.staticsName:""}<p></p>sn:${item.staticsId}</div>`:"<div>其他</div>";
              }
              item.staticsName=name;
              return item;
            });

          } else {
            Toast(res.msg);
          }
        })
        .catch((err) => {

        });
    },
    storeDataSort(){
      let sortField="";//排序字段
      if(this.tabCompent3.tabIndex==0){
        sortField="receiveMoney";
      }else if(this.tabCompent3.tabIndex==1){
        sortField="orderPrice";
      }else if(this.tabCompent3.tabIndex==2){
        sortField="unitPrice";
      }
      const dataList=this.storeDataList.sort((a,b)=>{
        return b[sortField]-a[sortField];
      });
      this.storeDataList=dataList;
    },
    getStoreData() {
      var startDate = this.startDate;
      var endDate = this.endDate;
      var currentPage = 1;
      var pageSize = 10;
      this.storeDataList = [];
      this.ajax({
        url: "/merchantApp/businessReport/queryStoreDataNew.do?startDate=" + startDate + "&endDate=" + endDate + "&currentPage=" + currentPage + "&pageSize=" + pageSize + "&dateFlag=0",
        type: "get",
        controlLoading: true
      })
        .then((res) => {
          if (res.success) {

            var data = res.resultObject;
            if (data != null && data.dataList.length > 0) {
              data.dataList.map((item) => {
                let shopAnountCnt = item.shopAnountCnt == null ? 0 : (parseFloat(item.shopAnountCnt) * 100).toFixed(2);
                let orderAnountCnt = item.orderAnountCnt == null ? 0 : (parseFloat(item.orderAnountCnt) * 100).toFixed(2);
                item.name = item.shopName;
                item.receiveMoney = item.shopAmount;
                item.receiveProportion = shopAnountCnt + "%";
                item.orderPrice = item.orderConsumAmount;
                item.orderPriceProportion = orderAnountCnt + "%";
                item.unitPrice = item.orderConsumCnt;
                return item;
              });
              this.storeDataList = this.storeDataList.concat(data.dataList);
              this.storeDataSort();
              this.loading = false;
            }
          }
        })
        .catch((err) => {

        });
    },
    reqAll() {
      if (moment(this.startDate).isSame(moment(), "d")) {//日期是否为今天
        this.dateFlag = "1";
      } else {
        this.dateFlag = "0";
      }
      this.getSumData(()=>{
          this.getOrderSource();
      });
      this.getStoreData();
      if (this.dateFlag != "1") {
        this.getOrderData();
        this.getIncomeData();
      }
    }
  },
  mounted() {
      this.reportFilter = {
      reportType: "day",
      dateLabel: moment().format("YYYY-MM-DD") + "(今天)"
    }
    this.checkUserRole();
    this.bindNewOrderEvent();
    this.menuBtnBottom = this.$refs.menuBtn.getBoundingClientRect().bottom;
  },
  created() {

  },
  components: {
    customHeader,
    StoreChoice,
    DateChoice,
    InfoModal,
    "v-loadmore": Loadmore,
    swiper,
    swiperSlide,
    storeCompare,
    menuList,
    calendarDay,
    calendarWeek,
    calendarMonth,
    orderSource
  }
};
</script>
<style lang='scss' scoped>
@import "businessAnalysis";
</style>
